<template>
    <div class="update-to-device-container">
        <div class="update-header">
            <h2>更新到设备</h2>
            <p>从服务器下载配置和数据到本地设备</p>
        </div>
        
        <div class="download-action">
            <a-button 
                type="primary" 
                icon="download"
                size="large"
                :loading="updating"
                @click="startUpdate"
            >
                开始更新
            </a-button>
        </div>
        
        <!-- 下载历史 -->
        <div class="download-history">
            <h3>更新历史</h3>
            <a-table
                :columns="historyColumns"
                :data-source="updateHistory"
                :pagination="{ pageSize: 5 }"
                size="small"
            >
                <template slot="status" slot-scope="text">
                    <a-tag :color="text === 'success' ? 'green' : text === 'failed' ? 'red' : 'orange'">
                        {{ text === 'success' ? '成功' : text === 'failed' ? '失败' : '进行中' }}
                    </a-tag>
                </template>
            </a-table>
        </div>
    </div>
</template>

<script>
import { mapGetters } from 'vuex'
import DeviceTabManager from '@/api/TabManager/DeviceTabManager'

export default {
    name: 'UpdateToDevice',
    props: {
        ipAddress: {
            type: String,
            required: true
        },
        port: {
            type: String,
            required: true
        }
    },
    data() {
        return {
            updating: false,
            updateHistory: [],
            historyColumns: [
                {
                    title: '时间',
                    dataIndex: 'time',
                    key: 'time'
                },
                {
                    title: '更新项目',
                    dataIndex: 'items',
                    key: 'items'
                },
                {
                    title: '状态',
                    dataIndex: 'status',
                    key: 'status',
                    scopedSlots: { customRender: 'status' }
                }
            ],
            statusCheckTimer: null,
            deviceTabManager: new DeviceTabManager()
        }
    },
    computed: {
        ...mapGetters('groupTree', ['selectedDeviceInfo'])
    },
    beforeDestroy() {
        this.clearStatusCheck()
    },
    methods: {
        // 开始更新到设备
        async startUpdate() {
            if (!this.selectedDeviceInfo) {
                this.$message.error('请先选择设备')
                return
            }

            // 验证网络参数
            if (!this.ipAddress || !this.ipAddress.trim()) {
                this.$message.error('请先输入IP地址')
                return
            }

            if (!this.port || !this.port.trim()) {
                this.$message.error('请先输入端口号')
                return
            }

            try {
                this.updating = true
                
                const data = {
                    deviceId: this.selectedDeviceInfo.id,
                    deviceName: this.selectedDeviceInfo.name,
                    ip: this.ipAddress.trim(),
                    port: this.port.trim()
                }

                console.log('🔄 [UpdateToDevice] 开始更新到设备:', data)
                const response = await this.deviceTabManager.updateToDevice(JSON.stringify(data))

                if (response.code === 0) {
                    this.$message.info('更新指令已发送，正在等待更新...')
                    this.startStatusCheck()
                } else {
                    this.handleUpdateFailure('更新指令发送失败: ' + response.msg)
                }
            } catch (error) {
                this.handleUpdateFailure('更新失败: ' + error.message)
            }
        },

        // 开始状态检查
        startStatusCheck() {
            this.clearStatusCheck()
            
            this.statusCheckTimer = setInterval(async() => {
                try {
                    const params = {
                        deviceId: this.selectedDeviceInfo.id,
                        ip: this.ipAddress,
                        port: this.port
                    }
                    
                    const response = await this.deviceTabManager.getDeviceUpdateStatus(params)

                    if (response.code === 0) {
                        const status = response.data
                        
                        if (status.completed) {
                            this.handleUpdateComplete(status.success)
                        }
                    }
                } catch (error) {
                    console.error('❌ [UpdateToDevice] 获取更新状态失败:', error)
                }
            }, 2000)

            // 设置超时保护
            setTimeout(() => {
                if (this.updating) {
                    this.handleUpdateFailure('更新超时，请检查设备连接')
                }
            }, 5 * 60 * 1000) // 5分钟超时
        },

        // 清除状态检查
        clearStatusCheck() {
            if (this.statusCheckTimer) {
                clearInterval(this.statusCheckTimer)
                this.statusCheckTimer = null
            }
        },

        // 处理更新完成
        handleUpdateComplete(success) {
            this.clearStatusCheck()
            this.updating = false
            
            const message = success ? '更新到设备成功' : '更新到设备失败'
            this.$message[success ? 'success' : 'error'](message)

            // 更新最新记录的状态
            if (this.updateHistory.length > 0) {
                this.updateHistory[0].status = success ? 'success' : 'failed'
            }
        },

        // 处理更新失败
        handleUpdateFailure(errorMessage) {
            this.clearStatusCheck()
            this.updating = false
            this.$message.error(errorMessage)

            // 更新最新记录的状态或添加失败记录
            if (this.updateHistory.length > 0 && this.updateHistory[0].status === 'updating') {
                this.updateHistory[0].status = 'failed'
            } else {
                this.addUpdateRecord('failed')
            }
        },

        // 添加更新记录
        addUpdateRecord(status) {
            const record = {
                id: Date.now(),
                time: new Date().toLocaleString(),
                items: '设备配置, 参数设置',
                status: status
            }
            this.updateHistory.unshift(record)
        }
    }
}
</script>

<style scoped>
.update-to-device-container {
    background: white;
    border-radius: 8px;
    padding: 24px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    max-width: 800px;
    margin: 0 auto;
}
.update-header {
    margin-bottom: 24px;
    text-align: center;
}
.update-header h2 {
    margin: 0 0 8px 0;
    color: #333;
    font-size: 20px;
}
.update-header p {
    margin: 0;
    color: #666;
    font-size: 14px;
}
.download-action {
    text-align: center;
    margin-bottom: 32px;
}
.download-history {
    margin-top: 24px;
}
.download-history h3 {
    margin-bottom: 16px;
    color: #333;
    font-size: 16px;
    text-align: center;
}
</style> 